
package reppconn;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.DBWriter;
import model.Document;
import model.RIModel;
import model.Terme;
import org.annolab.tt4j.TreeTaggerException;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


public class ContentHandler extends DefaultHandler {
    private DBWriter db;
    private RIModel model;
    private XPath currentXPath;
    private String currentDocument;
    private StringBuffer buff;
    private boolean isTitre = false;
    private boolean isDescription = false;
    private boolean isP = false;
    private String titre = null;
    private ArrayList<String> tokenNonLemm;
    private LemmatiseurHandler lemMoiCa;
    private StopList arrayStopList;
    private Document doc;
    
    public ContentHandler(RIModel model) {
        this.model = model;
        this.currentXPath = new XPath();
        lemMoiCa = new LemmatiseurHandler();
        tokenNonLemm = new ArrayList<String>();
        arrayStopList = new StopList();
    }
    
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                
        this.currentXPath.goIn(qName);
        this.model.addNode(qName, currentXPath.getXPath());
        if(qName.equals("TITRE")){
            isTitre = true; 
        }
        
        //buff = new StringBuffer();
        
        if(qName.equals("DESCRIPTION")){
            isDescription = true;
        }
        
        if(qName.equals("P")){
                isP = true; 
        }
    }
    
    //détection fin de balise
	public void endElement(String uri, String localName, String qName)
			throws SAXException{
            try {             
                lemMoiCa.setListTermeNonLem(tokenNonLemm);
                
                if(!lemMoiCa.getListTermeLem().isEmpty()){
                   lemMoiCa.clearListTermLem(); 
                }
                lemMoiCa.lemmatiser();     
                tokenNonLemm.clear();
                
                ArrayList<String> listTermeLem = new ArrayList<String>();
                String currentToken = null; 
                for(int j=0; j < lemMoiCa.getListTermeLem().size(); j++){

                    currentToken = lemMoiCa.getListTermeLem().get(j);

                    if(!lemMoiCa.isSmallerToken(currentToken)){
                        listTermeLem.add(lemMoiCa.couperToken(currentToken));       
                    }else{
                        listTermeLem.add(currentToken);
                    }  
                }
                //System.out.println("TERM LEM => "+listTermeLem);
                //Ajout des termes lemmatises ds la hashmap
                for(int n=0; n < listTermeLem.size(); n++){
                    //System.out.println("TERM LEM => "+listTermeLem.get(n));
                    model.addTerme(listTermeLem.get(n),n);    
                }  
                //calcul Tf 
                 //System.out.println("size list => "+ listTermeLem.size());     
                /*for(String s : listTermeLem){
                    double val_Tf=0;
                    Terme t;
                    t = model.getTermeFromTC(s);
                    
                    val_Tf = t.calculFreqTerme(model.getCurrentNodeId(),listTermeLem.size());
                    t.addTfdsList(val_Tf);
                    //System.out.println("Term => "+s+" Val TF => "+val_Tf);
                }*/
                
                
                
            } catch (IOException ex) {
                Logger.getLogger(ContentHandler.class.getName()).log(Level.SEVERE, null, ex);
            } catch (TreeTaggerException ex) {
                Logger.getLogger(ContentHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
            this.currentXPath.goBack();
	}
        
	//détection de caractères
    @Override
	public void characters(char[] ch,int start, int length) {
            String[] termes;
            termes = new String(ch,start,length).split("[ ,;.\\\\:?!\'\"\t\n()]+",-1);
/*<<<<<<< .mine
            for (int i=0; i<termes.length; i++) { 
                termes[i] = termes[i].toLowerCase();
                model.addTerme(termes[i],this.currentDocument,this.currentXPath.getXPath(),i); 
=======*/
            for (int i=0; i<termes.length; i++) {      
                //Si terme n'a qu'un caractere alors on ne s'en occupe pas
                if(termes[i].length() > 1){
                    //Si le terme du document appartient a la Stop Liste alors
                    //on n'ajoute pas ce terme a notre liste de tokenNonLemm
                    if(!arrayStopList.isTokenStopList(termes[i].toLowerCase())){
                        tokenNonLemm.add(termes[i].toLowerCase()); 
                    }   
                } 

            }
	}

    @Override
	public void startDocument() throws SAXException {
        System.out.println("Document : "+this.currentDocument);
		model.addDocument(this.currentDocument);
                this.currentXPath.reset();
                //this.doc = new Document(this.currentDocument);
	}

    @Override
	public void endDocument() throws SAXException {
            double ponderation = 0;
            //Longueur du DOC = Nb de termes
            double sizeDoc = (double)model.getListTermes().size();
            System.out.println("Longueur du DOC =>"+ sizeDoc);
            //this.doc.setLongueur(sizeDoc);

            for(Terme t : model.getListTermes()){
                //old : t.addDocumenttoList(this.doc);
                //System.out.println("T => "+t.getWord()+" -- Compt => "+t.getCompteur()+" TF => "+t.calculFreqTerme(sizeDoc)+" IDF => "+t.calculIDF());
                //System.out.println("SIZE LIST DOC => "+t.getListDocs().size());


                //old : ponderation = t.calculFreqTerme(sizeDoc) * t.calculIDF();

                //old :ponderation = t.calculFreqTerme(sizeDoc) * t.calculIDF();


                //System.out.println("PONDE => "+ponderation);
            }
           
               
                /*try {
                 * //!\\ Voir ou je peux faire ca sans avori de pb...
                    lemMoiCa.destroyLemmatiser();
                   
                } catch (IOException ex) {
                    Logger.getLogger(ContentHandler.class.getName()).log(Level.SEVERE, null, ex);
                } catch (TreeTaggerException ex) {
                    Logger.getLogger(ContentHandler.class.getName()).log(Level.SEVERE, null, ex);
                }*/
          
	}
    
    public void setCurrentDocument(String name) {
        this.currentDocument = name;
    }
    
    

}
